import '../global'
import axios, { AxiosError } from "axios";
import { MessageApiInjection } from "naive-ui/es/message/src/MessageProvider";
import { userStore } from '../store/userStore';

export const mainApi = import.meta.env.DEV ? 'http://localhost:8080/api' : 'http://localhost:8080/api'
export const imageApi = import.meta.env.DEV ? 'http://localhost:8080' : 'http://localhost:8080'

const userInfo = userStore()
const rq = axios.create({ baseURL: mainApi });

export function post(api: string, payload: Object = {}) {
    return rq.post(api, payload);
}

export function get(api: string, p: Array<any> = []) {
    return rq.get(api, { params: p });
}


rq.interceptors.request.use((config) => {
    if (userInfo.isLogin) config.headers.Authorization = userInfo.tokenVal as string
    return config
})

rq.interceptors.response.use(
    function (res) {
        return res.data
    },
    function (err: AxiosError) {
        const data: any = err.response?.data
        const message: MessageApiInjection = window.message
        message.warning(data.message)
    }
)